package cn.thinkluck.pattern.proxy.dynamic.cglib;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author liutao
 * @DateTime 2024/7/20 下午4:15
 */
@Slf4j
public class CacheMethodInterceptor implements MethodInterceptor {
    private final Map<String, String> cache = new HashMap<>();
    private final DatabaseQuery databaseQuery;
    public CacheMethodInterceptor(DatabaseQuery databaseQuery) {
        this.databaseQuery = databaseQuery;
    }
    /**
     *
     * @param o 代理类
     * @param method 即将被调用的方法
     * @param objects 调用方法时传递的实际参数数组
     * @param methodProxy 被代理类原始方法的对象
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        //1. 判断是哪个方法
        if ("query".equals(method.getName())) {
            String key = objects[0].toString();
            //2. 查询缓存
            String data = cache.get(key);
            if (data != null) {
                log.info("命中缓存");
                return data;
            }
            log.info("未命中缓存");
            //3. 未命中缓存 调用被代理对象查询数据库
            data = (String) methodProxy.invoke(databaseQuery, objects);
            cache.put(key, data);
            return data;
        }
        //4. 如果不是要被代理的方法，就维持原样调用
        return methodProxy.invoke(databaseQuery, objects);
    }
}
